'use strict';
var http = require("http"),https = require("https"), url = require("url"), fs = require('fs');

module.exports = (request, response, epath)=>{
    let site = require("../config/http");
    if(epath) request.GET.pathname += epath;
    if(request.GET.pathname == "/") request.GET.pathname = "/index.html";
    console.log(request.SITE["root"] + request.GET.pathname);
    fs.stat(request.SITE["root"] + request.GET.pathname, function(err, stats){
        if(err)
        {
            if(err.code == 'ENOENT')
            {
                let options = site[request.headers.host];
                options.path = request.url;
                options.method = request.method;

                if(options.port == 443)
                    https.request(options, hld).end();
                else
                    http.request(options, hld).end();

                function hld(res)
                {
                    response.statusCode = res.statusCode;
                    if(response.statusCode == 302) response.setHeader("location", res.headers["location"]);
                    res.pipe(response);
                    console.log("write file ", request.GET.pathname);
                    let cd = Buffer.allocUnsafe(0), ecd = null;
                    if(res.headers["content-type"] && res.headers["content-type"].indexOf("image/") != -1){
                        res.setEncoding("binary");
                        ecd = "binary";
                    } 
                    res.on("data", (chunk)=>{
                        cd = Buffer.concat([cd,chunk],cd.length+chunk.length);
                    });
                    res.on("end", ()=>{
                        if(res.statusCode == 200)
                        {
                            const cdir = require("./cdir");
                            cdir(request.SITE["root"], request.GET.pathname, ()=>{
                                fs.writeFile(request.SITE["root"] + request.GET.pathname, cd, ecd, function(err){
                                    if(err)
                                    {
                                        console.log("write file error", request.url, err);
                                        return;
                                    }
                                    console.log("write end", request.url);
                                });
                            });
                        }
                    });
                }
            }
            return;
        }
        if(stats.isDirectory()) request.GET.pathname += "/index.html";
        let stream = fs.createReadStream(request.SITE["root"] + request.GET.pathname);
        stream.pipe(response);
    });
}